package cn.gzsf.csmall.passport.security;

import cn.gzsf.csmall.passport.mapper.AdminMapper;
import cn.gzsf.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    //loadUserByUsername方法在登录时由Security自动调用
    //查询用户名和密码，按照规则返回UserDetails对象，由Security自动匹配
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("Spring Security框架自动调用了UserDetailServiceImpl.loadUserByUsername方法，用户名:{}",username);
        //根据用户名从数据库中查询匹配的用户信息
        AdminLoginInfoVO loginInfo = adminMapper.getLoginInfoByUsername(username);
        log.debug("根据用户名【{}】从数据库中查询匹配的管理员信息，结果：{}",username,loginInfo);
        if(loginInfo==null){
            log.debug("此用户名没有匹配的用户的数据，将会返回null");
            return null;
        }
        log.debug("用户名匹配成功，准备返回此用户名匹配的UserDetails类型的对象");

        //取出管理员信息中的权限信息
        List<String> permissions = loginInfo.getPermissions();
        //创建权限集合
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for(String permission:permissions){//将权限字符串封装成权限对象，并添加到集合中
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        AdminDetails userDetails = new AdminDetails(
                loginInfo.getId(),loginInfo.getUsername(),
                loginInfo.getPassword(),loginInfo.getEnable()==1,authorities
        );
        /*UserDetails userDetails = User.builder()
                .username(loginInfo.getUsername())
                .password(loginInfo.getPassword())
                .disabled(loginInfo.getEnable()==0)//账号是否禁用
                .accountLocked(false)//账号状态是否被锁定
                .credentialsExpired(false)//账号的凭证是否过期
                .authorities("这是一个临时用的山寨的权限")
                .build();*/
        log.debug("即将向Spring Security返回UserDetails类型的对象：{}",userDetails);
        return userDetails;
    }
}
